<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row>
				<div class="flex justify-between w-full mb8">
					<el-space>
						<el-popover trigger="click" :width="550" placement="bottom-start">
							<el-form :inline="false" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef" label-width="90px" size="small">
								<el-row>
									<el-col :span="12" class="mb20">
										<el-form-item label="所属单位" prop="deptId">
											<el-tree-select
												v-model="state.queryForm.deptId"
												:data="parentData"
												:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
												clearable
												filterable
												check-strictly
												multiple
												tag-type="success"
												:render-after-expand="false"
												placeholder="请选择所属单位"
												:teleported="false"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="单位限制" prop="deptLimit">
											<el-select clearable v-model="state.queryForm.deptLimit" :teleported="false">
												<el-option label="包含下级单位设备" :value="10" />
												<el-option label="仅本单位设备" :value="20" />
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="类型" prop="deviceTypeId">
											<el-select
												v-model="state.queryForm.deviceTypeId"
												clearable
												filterable
												placeholder="请选择设备类型"
												@change="getModelList"
												:teleported="false"
											>
												<el-option
													v-for="item in deviceTypeList"
													:key="item.id"
													:value="item.id"
													:label="item.typeName"
													:disabled="item.state === 20"
												/>
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :span="12" class="mb20">
										<el-form-item label="设备型号" prop="deviceModelId">
											<el-select v-model="state.queryForm.deviceModelId" clearable filterable placeholder="请选择设备型号" :teleported="false">
												<el-option
													v-for="item in deviceModelList"
													:key="item.id"
													:value="item.id"
													:label="item.deviceModelName"
													:disabled="item.state === 20"
												/>
											</el-select>
										</el-form-item>
									</el-col>
									<el-col :span="12" class="mb20">
										<el-form-item label="到期时间" prop="platformExpireDate">
											<el-date-picker
												placeholder="选择到期时间"
												type="date"
												v-model="state.queryForm.platformExpireDate"
												value-format="YYYY-MM-DD"
												:teleported="false"
											/>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>

							<template #reference>
								<el-button link type="primary"
									>高级搜索<el-icon><ArrowDown /></el-icon>
								</el-button>
							</template>
						</el-popover>
						<el-input placeholder="请输入IMEI号" v-model="state.queryForm.imei" />
						<el-button type="primary" @click="getDataList(true)">搜索</el-button>
						<el-button icon="refresh" @click="resetQuery()"></el-button>
					</el-space>
					<div>
						<el-button type="primary" icon="CirclePlus" class="mr-2" @click="formDialogRef.openDialog(currentRow)" :disabled="!currentRow.id"
							>分配语音短信数</el-button
						>
					</div>
				</div>
			</el-row>
			<!-- <el-row>
				<div class="mb8" style="width: 100%">
					<el-button
						icon="folder-add"
						type="primary"
						class="ml10"
						@click="formDialogRef.openDialog()"
						v-auth="'platform_basicExpensesDviceConfig_add'"
					>
						新 增
					</el-button>
					<el-button
						plain
						:disabled="multiple"
						icon="Delete"
						type="primary"
						v-auth="'platform_basicExpensesDviceConfig_del'"
						@click="handleDelete(selectObjs)"
					>
						删除
					</el-button>
					<right-toolbar
						v-model:showSearch="showSearch"
						:export="'platform_basicExpensesDviceConfig_export'"
						@exportExcel="exportExcel"
						class="ml10 mr20"
						style="float: right"
						@queryTable="getDataList"
					></right-toolbar>
				</div>
			</el-row> -->
			<el-table
				:data="state.dataList"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				highlight-current-row
				@current-change="handleCurrentChange"
				row-key="id"
			>
				<!-- <el-table-column type="selection" width="40" align="center" /> -->
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="imei" label="IMEI" show-overflow-tooltip width="200" />
				<el-table-column prop="deviceType" label="类型-型号" show-overflow-tooltip width="220">
					<template #default="{ row }">
						<span>
							{{ row.deviceType }}
							-
							{{ row.deviceModelName }}
						</span>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="注册日期" show-overflow-tooltip width="160" />
				<el-table-column prop="createTime" label="启用日期" show-overflow-tooltip width="160" />
				<el-table-column prop="customerDeptName" label="所属单位" show-overflow-tooltip width="220" />
				<el-table-column prop="deliveryMethod" label="代付状态" width="100">
					<template #default="{ row }">
						<div>
							<el-button link v-if="row.deliveryMethod === 20" type="primary" size="small">代付</el-button>
							<span v-else class="text-info" size="small">配送</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="expirationDate" label="代付到期时间" show-overflow-tooltip width="160">
					<template #default="{ row }">
						<span class="text-error" v-if="isOverDate(row.expirationDate)">已到期</span>
						<span v-else>{{ row.expirationDate }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="ttsRemainNum" label="语音剩余（分钟）" show-overflow-tooltip width="160">
					<template #default="{ row }">
						<span>{{ row.ttsRemainNum === 999999 ? '无限制' : row.ttsRemainNum }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="smsRemainNum" label="短信剩余（条）" show-overflow-tooltip width="160">
					<template #default="{ row }">
						<span>{{ row.smsRemainNum === 999999 ? '无限制' : row.smsRemainNum }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="platformYears" label="平台使用年限" show-overflow-tooltip width="120" />
				<el-table-column prop="platformExpireDate" label="平台到期时间" show-overflow-tooltip width="180">
					<template #default="{ row }">
						<span class="text-error" v-if="isOverDate(row.platformExpireDate)">已到期</span>
						<span v-else>{{ row.platformExpireDate }}</span>
					</template>
				</el-table-column>

				<!-- <el-table-column prop="deviceId" label="设备id" show-overflow-tooltip />
				<el-table-column prop="deptId" label="所属单位id" show-overflow-tooltip />
				<el-table-column prop="giveDeptId" label="赠送单位" show-overflow-tooltip />
				<el-table-column prop="type" label="分配方式 10短信 20语音" show-overflow-tooltip />
				<el-table-column prop="deliveryMethod" label="配置方式(10配送；20代付)" show-overflow-tooltip />
				<el-table-column prop="deliveryNum" label="赠送数量，无限制为 999999" show-overflow-tooltip />
				<el-table-column prop="useRemainNum" label="使用剩余数量，无限制为 999999" show-overflow-tooltip />
				<el-table-column prop="remainNum" label="剩余数量，无限制为 999999" show-overflow-tooltip />
				<el-table-column prop="totalLimit" label="总限制，无限制为 999999" show-overflow-tooltip />
				<el-table-column prop="totalLimitRemain" label="总限制剩余次数" show-overflow-tooltip />
				<el-table-column prop="sumDay" label="日限，无限制为 999999" show-overflow-tooltip />
				<el-table-column prop="sumDayRemain" label="日限剩余次数" show-overflow-tooltip />
				<el-table-column prop="sumMonth" label="月限，无限制为 999999" show-overflow-tooltip />
				<el-table-column prop="sumMonthRemain" label="月限剩余次数" show-overflow-tooltip />
				<el-table-column prop="sort" label="排序" show-overflow-tooltip /> -->
				<el-table-column label="操作" width="90" fixed="right">
					<template #default="scope">
						<!-- <el-button
							icon="edit-pen"
							text
							type="primary"
							v-auth="'platform_basicExpensesDviceConfig_edit'"
							@click="formDialogRef.openDialog(scope.row.id)"
							>编辑</el-button
						>
						<el-button icon="delete" text type="primary" v-auth="'platform_basicExpensesDviceConfig_del'" @click="handleDelete([scope.row.id])"
							>删除</el-button
						> -->
						<el-button text type="primary" @click.stop="handleRecord(scope.row)">赠送记录</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
	</div>
</template>

<script setup lang="ts" name="systemBasicExpensesDviceConfig">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs } from '/@/api/tariff/basicExpensesDviceConfig';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { deptTree } from '/@/api/admin/dept';
import { fetchListAll } from '/@/api/platform/basicDeviceType';
import { fetchListAll as fetchAllModelList } from '/@/api/platform/basicDeviceModel';
import { useRouter } from 'vue-router';
const router = useRouter();
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典

// 定义变量内容
const formDialogRef = ref();
// 搜索变量
const queryRef = ref();
const parentData = ref([]);
const deviceTypeList: any = ref([]);
const deviceModelList: any = ref([]);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	descs: ['create_time'],
});

const currentRow = ref({ id: null });
//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	currentRow.value = { id: null };
	state.queryForm.imei = null;
	getDataList();
};

// 导出excel
const exportExcel = () => {
	downBlobFile('/platform/basicExpensesDviceConfig/export', Object.assign(state.queryForm, { ids: selectObjs }), 'basicExpensesDviceConfig.xlsx');
};
const handleCurrentChange = (val: any) => {
	currentRow.value = val;
};
// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm('此操作将永久删除');
	} catch {
		return;
	}

	try {
		await delObjs(ids);
		getDataList();
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
// 判断到期
const isOverDate = (date: string) => {
	if (!date) return false;
	if (new Date(date).getTime() > new Date().getTime()) return false;
	return true;
};
const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};
getDeptData();
// 获取设备数据
const getDeviceTypes = () => {
	fetchListAll({ state: 10 }).then((res) => {
		deviceTypeList.value = res.data;
	});
};
// 查询设备型号
const getModelList = (deviceTypeId: string) => {
	state.queryForm.deviceModelId = null;
	fetchAllModelList({ deviceTypeId, state: 10 }).then((res) => {
		deviceModelList.value = res.data;
	});
};
getDeviceTypes();
// 赠送记录
const handleRecord = (row: any) => {
	router.push({
		path: '/tariff/basicExpensesDviceConfig/detail',
		query: {
			id: row.id,
			deviceId: row.deviceId,
			deptId: row.deptId,
			imei: row.imei,
			deviceModelName: row.deviceModelName,
			deviceType: row.deviceType,
		},
	});
};
</script>
